package com.atguigu.day04;

import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

//有界流WordCount
public class Flink04_RuntimeMode {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //TODO 设置执行模式
        env.setRuntimeMode(RuntimeExecutionMode.BATCH);

        //将并行度设置为1 在企业中比如与kafka数据源对接，通常和topic分区数保持一致
        env.setParallelism(1);

        //2.从文件读取数据
        DataStreamSource<String> streamSource = env.readTextFile("input/word.txt");
//        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3.使用FlatMap将数据按照空格切分，然后组成Tuple2元组
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordToOneDStream = streamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                //将数据按照空格切分
                String[] words = value.split(" ");
                //遍历字符串数组获取每一个元素（单词）
                for (String word : words) {
                    //将每个单词组成Tuple2元组返回
                    out.collect(Tuple2.of(word, 1));
                }
            }
        });

        //4.将相同单词的数据聚合到一块
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = wordToOneDStream.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            @Override
            public String getKey(Tuple2<String, Integer> value) throws Exception {
                return value.f0;
            }
        });

//        KeyedStream<Tuple2<String, Integer>, Tuple> keyedStream1 = wordToOneDStream.keyBy(0);

        //5.进行累加操作
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = keyedStream.sum(1);

        //6.打印到控制台
        result.print();

        env.execute();
    }
}
